package com.wankuma.hcm.midlet.metwit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class BinaryUtil {

	public static byte[] stringToUTFBytes(String str) {
		ByteArrayOutputStream bos = null;
		DataOutputStream dos = null;

		byte[] output = null;
		try {
			bos = new ByteArrayOutputStream();
			dos = new DataOutputStream(bos);
			dos.writeUTF(str);
			byte[] tmp1 = bos.toByteArray();
			output = new byte[tmp1.length - 2];
			for (int i = 2; i < tmp1.length; i++) {
				output[i - 2] = tmp1[i];
			}
		} catch (Exception e) {
			Alerter.alert(e.toString());
		} finally {
			try {
				if (dos != null)
					dos.close();
				if (bos != null)
					bos.close();
			} catch (Exception e) {
				Alerter.alert(e.toString());
			}
		}
		return output;
	}

	public static byte[] intToByte(int num) {
		ByteArrayOutputStream bos = null;
		DataOutputStream dos = null;

		byte[] output = null;
		try {
			bos = new ByteArrayOutputStream();
			dos = new DataOutputStream(bos);
			dos.writeInt(num);
			output = bos.toByteArray();
		} catch (Exception e) {
			Alerter.alert(e.toString());
		} finally {
			try {
				if (dos != null)
					dos.close();
				if (bos != null)
					bos.close();
			} catch (Exception e) {
				Alerter.alert(e.toString());
			}
		}
		return output;
	}

	public static int byteToInt(byte[] bin) {
		ByteArrayInputStream bis = null;
		DataInputStream dis = null;
		int output = 0;
		try{
			bis = new ByteArrayInputStream(bin);
			dis = new DataInputStream(bis);
			output = dis.readInt();
		}catch (Exception e) {
			Alerter.alert(e.toString());
		}
		return output;
	}
}
